package com.suishoupai.xmb.service;


import com.suishoupai.xmb.exception.XmbException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@Service
public class ImageService {
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpService httpService;

    @Value("${qiniu.down-domain}")
    private String qiniuDownDomain;

    /**
     * 从七牛云下载图片并返回
     *
     * @param key 图片key
     * @throws XmbException
     */
    public void fillImage8qiniukey(String key) throws XmbException {
        InputStream inputStream = null;
        response.setContentType("image/png");
        try {
            ImageIO.write(ImageIO.read(inputStream = httpService.get8stream(qiniuDownDomain + key)), "png", response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw XmbException.newError(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
